/* @module 颜色系统 */
import { hexToRgb, rgbToHex, lighten, darken, generateColorVariants, calculateDarkColor, toHexColor } from '../../color/helpers';
import { baseColors, neutralColors } from './base-colors';
import { ref } from 'vue';

// 合并基础颜色和中性色
const allLightColors = { ...baseColors, ...neutralColors };

// 存储自定义颜色的对象
const customColors: Record<string, string> = {};


// 生成亮色模式颜色变体
let lightColorsVariants: Record<string, string> = {};

// 生成暗黑模式颜色变体
let darkColorsVariants: Record<string, string> = {};

// 初始化颜色变体 - 处理基础颜色
Object.entries(baseColors).forEach(([name, color]) => {
  // 生成亮色模式变体
  const lightVariants = generateColorVariants(color, name);
  lightColorsVariants = { ...lightColorsVariants, ...lightVariants };

  // 基于亮色变体生成暗黑模式变体
  Object.entries(lightVariants).forEach(([variantName, variantColor]) => {
    darkColorsVariants[variantName] = calculateDarkColor(variantColor);
  });
});

// 初始化颜色变体 - 处理自定义颜色
const initializeCustomColors = () => {
  Object.entries(customColors).forEach(([name, color]) => {
    // 生成亮色模式变体
    const lightVariants = generateColorVariants(color, name);
    lightColorsVariants = { ...lightColorsVariants, ...lightVariants };

    // 基于亮色变体生成暗黑模式变体
    Object.entries(lightVariants).forEach(([variantName, variantColor]) => {
      darkColorsVariants[variantName] = calculateDarkColor(variantColor);
    });
  });
};

// 初始化自定义颜色
initializeCustomColors();

// 处理中性色
Object.entries(neutralColors).forEach(([name, color]) => {
  lightColorsVariants[name] = color;
  darkColorsVariants[name] = calculateDarkColor(color);
});

// 透明色特殊处理
darkColorsVariants['transparent'] = 'transparent';

/**
 * 注册自定义颜色
 * @param name 颜色名称
 * @param color 颜色值（十六进制格式）
 */
export function registerCustomColor(name: string, color: string): void {
  color = toHexColor(color);

  // 添加到自定义颜色对象
  customColors[name] = color;

  // 重新初始化自定义颜色变体
  initializeCustomColors();
}

/**
 * 批量注册自定义颜色
 * @param colors 颜色对象 {name: color, ...}
 */
export function registerCustomColors(colors: Record<string, string>): void {
  Object.entries(colors).forEach(([name, color]) => {
    registerCustomColor(name, color);
  });
}

// 合并亮色模式颜色和变体
const getMergedLightColors = () => {
  // 重置lightColorsVariants
  lightColorsVariants = {};

  // 重新处理基础颜色
  Object.entries(baseColors).forEach(([name, color]) => {
    const lightVariants = generateColorVariants(color, name);
    lightColorsVariants = { ...lightColorsVariants, ...lightVariants };
  });

  // 重新处理自定义颜色
  initializeCustomColors();

  return { ...allLightColors, ...customColors, ...lightColorsVariants };
};

// 合并暗黑模式颜色和变体
const getMergedDarkColors = () => {
  // 重置darkColorsVariants
  darkColorsVariants = {};

  // 重新处理基础颜色的暗色变体
  Object.entries(baseColors).forEach(([name, color]) => {
    const lightVariants = generateColorVariants(color, name);
    Object.entries(lightVariants).forEach(([variantName, variantColor]) => {
      darkColorsVariants[variantName] = calculateDarkColor(variantColor);
    });
  });

  // 重新处理自定义颜色的暗色变体
  initializeCustomColors();

  // 重新处理中性色
  Object.entries(neutralColors).forEach(([name, color]) => {
    darkColorsVariants[name] = calculateDarkColor(color);
  });

  // 透明色特殊处理
  darkColorsVariants['transparent'] = 'transparent';

  return { ...darkColorsVariants };
};

// 生成CSS变量名
const getCssVariableName = (key: string) => `--tui-color-${key.replace(/([A-Z])/g, '-$1').toLowerCase()}`;

/**
 * 颜色工具方法
 * @returns 包含所有颜色变量的对象、设置样式的方法和颜色操作函数
 */
export function useColor() {
  // 转换为CSS变量格式 - 使用ref使对象响应式
  const lightColorVars = ref<Record<string, string>>({});
  const darkColorVars = ref<Record<string, string>>({});

  // 暗黑模式状态
  const isDarkMode = ref(false);

  // 切换暗黑模式
  const toggleDarkMode = (enableDark?: boolean) => {
    const htmlElement = document.documentElement;
    const shouldBeDark = enableDark !== undefined ? enableDark : !isDarkMode.value;

    if (shouldBeDark) {
      htmlElement.classList.add('dark');
    } else {
      htmlElement.classList.remove('dark');
    }

    isDarkMode.value = shouldBeDark;
    localStorage.setItem('darkMode', shouldBeDark.toString());
  };

  // 初始化暗黑模式
  const initializeDarkMode = () => {
    const savedDarkMode = localStorage.getItem('darkMode');
    if (savedDarkMode !== null) {
      toggleDarkMode(savedDarkMode === 'true');
    }
  };

  // 设置颜色变量到document.documentElement
  const setColorVariables = () => {
    // 检查是否已存在样式元素，如果存在则移除
    const existingStyle = document.getElementById('tui-color-styles');
    if (existingStyle) {
      existingStyle.remove();
    }

    const styleElement = document.createElement('style');
    styleElement.id = 'tui-color-styles';

    // 获取最新的颜色数据
    const mergedLightColors = getMergedLightColors();
    const mergedDarkColors = getMergedDarkColors();

    // 清空之前的颜色变量
    lightColorVars.value = {};
    darkColorVars.value = {};

    // 生成亮色模式CSS变量
    const lightCss = [':root {'];
    Object.entries(mergedLightColors).forEach(([key, value]) => {
      const varName = getCssVariableName(key);
      lightColorVars.value[varName] = value;
      lightCss.push(`  ${varName}: ${value};`);
    });
    lightCss.push('}');

    // 生成暗黑模式CSS变量
    const darkCss = ['html.dark {'];
    Object.entries(mergedDarkColors).forEach(([key, value]) => {
      const varName = getCssVariableName(key);
      darkColorVars.value[varName] = value;
      darkCss.push(`  ${varName}: ${value};`);
    });
    darkCss.push('}');

    // 组合CSS文本
    styleElement.textContent = `${lightCss.join('\n')}\n\n${darkCss.join('\n')}`;

    // 将样式添加到文档
    document.head.appendChild(styleElement);
  };

  return {
    lightColors: lightColorVars,
    darkColors: darkColorVars,
    setColorVariables,
    getCssVariableName,
    isDarkMode,
    toggleDarkMode,
    initializeDarkMode,
    // 导出颜色操作函数，方便外部使用
    hexToRgb,
    rgbToHex,
    lighten,
    darken,
    generateColorVariants
  };
}

// 获取最新颜色常量的函数
export const getTuiColors = (): Record<string, string> => {
  return Object.freeze({ ...getMergedLightColors() }) as Record<string, string>;
};

export const getTuiDarkColors = (): Record<string, string> => {
  return Object.freeze({ ...getMergedDarkColors() }) as Record<string, string>;
};

// 导出默认颜色常量
// 使用Object.freeze确保是普通不可变Record对象
export const TuiColors = getTuiColors();
export const TuiDarkColors = getTuiDarkColors();



// 导出颜色操作工具函数
export const ColorUtils = {
  hexToRgb,
  rgbToHex,
  lighten,
  darken,
  generateColorVariants,
  registerCustomColor,
  registerCustomColors
};